package com.qs.worklog.dao.impl;

import java.util.Date;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.qs.worklog.dao.TaskDAO;
import com.qs.worklog.entity.Task;
import com.qs.worklog.util.DataSourceUtil;

public class ImplTaskDAO implements TaskDAO {

	public boolean saveTask(Task task){
		if(task.getId() == -1){
			String sql = "insert into task(uid,description,action_time,time_cost) values(?,?,?,?)";
			try {
				QueryRunner runner =  DataSourceUtil.getQueryRunner();
				runner.update(sql, task.getUid(), task.getDescription(), task.getActionTime(), task.getTimeCost());
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			}
		}else{
			String sql = "update task set description=?,action_time=?,time_cost=? where id=? ";
			try {
				QueryRunner runner =  DataSourceUtil.getQueryRunner();
				runner.update(sql, task.getDescription(), task.getActionTime(), task.getTimeCost(), task.getId());
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			}
		}
		return true;
	}
	
	public List<Task> findTasks(int userId, Date startDate, Date endDate){
		List<Task> tasks = new ArrayList<Task>();
		
		String sql = "select t.id,t.uid,t.description,t.action_time actionTime,t.time_cost timeCost, u.name userName from task t, user u where t.uid = u.id ";
		if(userId > 0){
			sql = sql + " and t.uid = " + userId;
		}
		int pCount = 0;
		if(startDate != null){
			sql = sql + " and t.action_time >= ?";
			pCount++;
		}
		if(endDate != null){
			sql = sql + " and t.action_time <= ?";
			pCount++;
		}
		ResultSetHandler<List<Task>> h = new BeanListHandler<Task>(Task.class);
		QueryRunner runner =  DataSourceUtil.getQueryRunner();
		Object[] paras = new Object[pCount];
		pCount = 0;
		if(startDate != null){
			paras[pCount] = startDate;
			pCount++;
		}
		if(endDate != null){
			paras[pCount] = endDate;
		}
		try {
			tasks = runner.query(sql, h, paras);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		Collections.sort(tasks);
		return tasks;
	}
	
	public List<Task> findTasks(int userId, Date actionTime) {
		return this.findTasks(userId, actionTime, actionTime);
	}
	public List<Task> findTasks(Date actionTime) {
		return this.findTasks(-1, actionTime, actionTime);
	}
	
	public List<Task> findTasks(Date startDate, Date endDate) {
		return this.findTasks(-1, startDate, endDate);
	}
	
	public boolean deleteByTid(int tid){
		String sql = "delete from task where id=?";
		try {
			QueryRunner runner =  DataSourceUtil.getQueryRunner();
			runner.update(sql, tid);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
}
